package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate  redisTemplate;
    /**
     * 获取登录验证码
     * @param
     * @param user
     * @return
     */

    //建议使用hash结构保存用户信息，以随机token为key存储用户数据，发请求携带token
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user){

        //获取手机号
        String phone = user.getPhone();
        if(phone!=null){
            //随机生成6位验证码
           String code = ValidateCodeUtils.generateValidateCode(6).toString();
           log.info("code:{}",code);
            //调用阿里云提供的短信API完成发送短信
           // SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //需要将生成的验证码保存到session
           // request.getSession().setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone,code,1800, TimeUnit.SECONDS);//30分钟内有效
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    /**
     * 登录
     * @param request
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request,@RequestBody Map<String,String> map){
        //获取页面数据
        String phone =map.get("phone");
        String code = map.get("code");
        //从session中获取值并进行比对
        //String codeInSession =(String) request.getSession().getAttribute(phone);//可存储redis
        String codeInRedis=(String) redisTemplate.opsForValue().get(phone);
        if(codeInRedis!=null&&code.equals(codeInRedis)){
            //根据phone查询是否为新用户，若新用户存储到user表中
            LambdaQueryWrapper<User> lqw=new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            if(user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            redisTemplate.delete(phone);//登录成功删除code缓存
            request.getSession().setAttribute("user",user.getId());
           return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
